package com.monkey.luffer.springboot.demo.basis.kcc.s3cmd;

import com.amazonaws.services.s3.AmazonS3;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


/**
 * @author jiahong.liu
 */
public class GenerateOkFile implements S3Oper{
    @Override
    public void request(AmazonS3 s3, MyCmd cmd) {
        String prefix = cmd.getPrefix();
        String srcPath = cmd.getSrcPath();
        File file = new File(srcPath);
        File[] array = file.listFiles();
        if (array == null) {
            System.out.println("路径下不存在文件");
            return;
        }
        Map<String, File> balance = new HashMap<>(8);
        Map<String, File> trx = new HashMap<>(8);
        Map<String, File> header = new HashMap<>(8);
        String sourceType = "";
        for (File value : array) {
            if (value.isFile() && !".DS_Store".equals(value.getName())) {
                // only take file name
                String name = value.getName();
                sourceType = name.split("_")[0];
                if (name.contains("ACCOUNTING_TRX") && name.contains(".TXT")) {
                    trx.put(name, value);
                } else if (name.contains("ACCOUNTING_BALANCE") && name.contains(".TXT")) {
                    balance.put(name, value);
                } else if (name.contains("ACCOUNTING_HEADER") && name.contains(".TXT")) {
                    header.put(name, value);
                }
            } else if (value.isDirectory()) {
                System.out.println("Not support directory");
            }
        }
        File file1 = new File(srcPath + "/" + sourceType + "_" + "AC_ACCOUNTING_BALANCE_" + prefix + ".OK");
        File file2 = new File(srcPath + "/" + sourceType + "_" + "AC_ACCOUNTING_TRX_" + prefix + ".OK");
        File file3 = new File(srcPath + "/" + sourceType + "_" + "AC_ACCOUNTING_HEADER_" + prefix + ".OK");
        StringBuilder content1 = new StringBuilder(sourceType + "|$|" + prefix + "|$|" + System.currentTimeMillis() + "\n");
        StringBuilder content2 = new StringBuilder(sourceType + "|$|" + prefix + "|$|" + System.currentTimeMillis() + "\n");
        StringBuilder content3 = new StringBuilder(sourceType + "|$|" + prefix + "|$|" + System.currentTimeMillis() + "\n");
        for (Map.Entry<String, File> entry: balance.entrySet()) {
            String name = entry.getKey();
            File tmpFile = entry.getValue();
            content1.append(name).append("|$|").append(getFileSha256(readFileToString(tmpFile)));
            content1.append("\n");
        }

        if(balance.size() > 0) {
            writeFile(file1, content1.toString());
        }

        for (Map.Entry<String, File> entry: trx.entrySet()) {
            String name = entry.getKey();
            File tmpFile = entry.getValue();
            content2.append(name).append("|$|").append(getFileSha256(readFileToString(tmpFile)));
            content2.append("\n");
        }

        if (trx.size() > 0) {
            writeFile(file2, content2.toString());
        }


        for (Map.Entry<String, File> entry: header.entrySet()) {
            String name = entry.getKey();
            File tmpFile = entry.getValue();
            content3.append(name).append("|$|").append(getFileSha256(readFileToString(tmpFile)));
            content3.append("\n");
        }

        if (header.size() > 0) {
            writeFile(file3, content3.toString());
        }
    }

    private String readFileToString(File file) {
        long fileLength = file.length();
        byte[] fileContent = new byte[(int) fileLength];
        try {
            FileInputStream in = new FileInputStream(file);
            int i = in.read(fileContent);
            System.out.println(i);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回文件内容,默认编码
        return new String(fileContent);
    }

    private String getFileSha256(String str) {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] b = str.getBytes(StandardCharsets.UTF_8);
            sha256.update(b);
            return toHex(sha256.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void writeFile(File file, String content) {
        try {
            if(!file.exists()){
                boolean flag = file.createNewFile();
                if (!flag) {
                    System.out.println("Create file failed, please check");
                    return;
                }
            }
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
            bufferWriter.write(content);
            bufferWriter.close();
            System.out.println("Write file done");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte datum : data) {
            String hex = Integer.toHexString(datum);
            if (hex.length() == 1) {
                sb.append("0");
            } else if (hex.length() == 8) {
                hex = hex.substring(6);
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase(Locale.getDefault());
    }

}
